import os

from sc_engine.repositories import Repository, use
from sc_engine.repositories.stores import PickleFileStore
from sc_engine.repositories.waiting import WaitingDataRepository
from sc_engine.repositories.idgen import IdGenRepository

from sc_engine.apps import messages as msgs

def make_app(app_name, root_config, config):
    data_dir = root_config['data_directory']

    store_filename = os.path.join(data_dir, app_name)
    store = PickleFileStore(store_filename)
    repo = Repository(store)

    app = MatchGameIdApp(repo)

    return {
        msgs.ProleagueMatchParseAnnouncement : app.proleague_match_parse_announcement,
        msgs.ProleagueGameParseAnnouncement : app.proleague_game_parse_announcement,
    }


class MatchGameIdApp(object):
    """Generate an id for matches as they are discovered."""

    def __init__(self, repo):
        self.repo = repo
        repo.add_repository('waiting', WaitingDataRepository)
        repo.add_repository('idgen', IdGenRepository)

    @use('repo', 'idgen', 'waiting')
    def proleague_match_parse_announcement(self, msg, ids, waiting_data):
        output = []

        data = {
            'league' : msg.league,
            'stage_path' : msg.stage_path,
            'team_one' : msg.team_one,
            'team_two' : msg.team_two
        }

        if data in ids:
            id = ids[data]
        else:
            id = ids.add(data)

        output.append(msgs.ProleagueMatchIdAnnouncement(id, **data))

        match_data = {
            'winner' : msg.winner,
            'winner_score' : msg.winner_score,
            'loser_score' : msg.loser_score,
        }

        output.append(msgs.ProleagueMatchDataAnnouncement(id, **match_data))
        return output + waiting_data.run(msg)
    
    @use('repo', 'idgen', 'waiting')
    def proleague_game_parse_announcement(self, msg, ids, waiting_data):
        output = []
        
        msg_dict = msg.to_dict()

        data = {
            'league' : msg_dict.pop('league'),
            'stage_path' : msg_dict.pop('stage_path'),
            'team_one' : msg_dict.pop('team_one'),
            'team_two' : msg_dict.pop('team_two'),
        }

        if data not in ids:
            waiting_data.add(msg, msgs.ProleagueMatchParseAnnouncement, data)
            return


        id = ids[data]
        return msgs.GameDataAnnouncement(id, **msg_dict)
